package com.nsharmon.model;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import com.nsharmon.dao.entity.Axiom;
import com.nsharmon.dao.entity.Project;
import com.nsharmon.model.transformer.Transformer;

public class LogicManager {
	private List<Transformer> transformers = new ArrayList<Transformer>();
	private Project project = null;
	private boolean generated = false;
	private Set<Axiom> generatedAxiomList;
	public LogicManager(Project project) {
		this.project = project;
	}
	
	public Set<Axiom> getGeneratedAxioms() {
		if(!generated) {
			boolean finished = (transformers.size() == 0);
			Set<Axiom> axiomList = new LinkedHashSet<Axiom>(project.getAxioms());
			generatedAxiomList = new LinkedHashSet<Axiom>();
			
			Iterator<Transformer> it = transformers.iterator();
			while(it.hasNext()) {
				if(!it.next().transformBegin()) {
					it.remove();
				}
			}
			
			while(!finished) {
				boolean addedAxioms = false;
				for(Transformer transformer : transformers) {
					Set<Axiom> extraAxioms = transformer.transform(axiomList);
					if(extraAxioms.size() > 0) {
						addedAxioms = true;
						axiomList.addAll(extraAxioms);
						generatedAxiomList.addAll(extraAxioms);
					}
				}
				finished = !addedAxioms;
			}
			
			for(Transformer transformer : transformers) {
				Set<Axiom> extraAxioms = transformer.transformEnd(axiomList);
				if(extraAxioms != null) {
					generatedAxiomList.addAll(extraAxioms);
				}
			}
		}
		return generatedAxiomList;
	}
	
	public void addTransformer(Transformer transformer) {
		generated = false;
		transformers.add(transformer);
	}

	public Set<Axiom> getAxioms() {
		return project.getAxioms();
	}
}
